package cn.dckeji.dcssm.controller;

import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName test
 * @Description TODO
 * @Author 41014
 * @Date 21:24
 * @Version 1.0
 **/
public class test {

    /**
     * @auther: Zww
     * 功能描述: 1、利用redis的watch功能，监控这个redisKey的状态值
    2、获取redisKey的值
    3、创建redis事务
    4、给这个key的值+1
    5、然后去执行这个事务，如果key的值被修改过则回滚，key不+1
     * @param: \
     * @return:
     * @date: 2019/7/31 21:28
     */
    /**
     * @auther: Zww
     * 功能描述: 
     * @param: 我开20个线程模拟10000个人并发来抢购
     * @return: 
     * @date: 2019/7/31 21:29
     */
    public static void main(String[] arg){
        String redisKey = "redisTest";
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        try {
            Jedis jedis = new Jedis("127.0.0.1",6379);
            jedis.auth("123456");
            jedis.set(redisKey,"");
            jedis.close();
        }catch (Exception e){
            e.printStackTrace();
        }

        for (int i=0;i<1000;i++){
            executorService.execute(()->{
                Jedis jedis1 = new Jedis("127.0.0.1",6379);
                jedis1.auth("123456");
                try {
                    jedis1.watch(redisKey);
                    String redisValue = jedis1.get(redisKey);
                   // int valInteger = Integer.valueOf(redisValue);
                    String userInfo = UUID.randomUUID().toString();
                    if (StringUtils.isBlank(redisValue)){
                        Transaction transaction = jedis1.multi();
                       // transaction.incr(redisKey);
                        transaction.set(redisKey,userInfo);
                        List list = transaction.exec();
                        if (list.size()!=0){
                            System.out.println("用户："+userInfo+"，秒杀成功！当前成功人："+(userInfo));
                        }else {
                            System.out.println("用户："+userInfo+"，秒杀失败");
                        }

                    }else {
                        System.out.println("秒杀结束");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    jedis1.close();
                }
            });
        }
        executorService.shutdown();
    }
}
